package org.jeecg.common.wx;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.Base64;
import org.apache.http.util.TextUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

public class tool {
    private static final String CONTENT_TYPE = "text/xml; charset=UTF-8";

    public static String isEmpty(Object obj) {
        String tag = "";
        if (obj != null && !TextUtils.isEmpty( String.valueOf( obj ) )) {
            tag = obj.toString();
        }
        return tag;
    }

    public static BufferedImage resize(BufferedImage source, int targetW, int targetH) {
        // targetW，targetH分别表示目标长和宽
        int type = source.getType();
        BufferedImage target = null;
        double sx = (double) targetW / source.getWidth();
        double sy = (double) targetH / source.getHeight();
        if (sx > sy) {
            sx = sy;
            targetW = (int) (sx * source.getWidth());
        }
        if (type == BufferedImage.TYPE_CUSTOM) {
            ColorModel cm = source.getColorModel();
            WritableRaster raster = cm.createCompatibleWritableRaster( targetW, targetH );
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();
            target = new BufferedImage( cm, raster, alphaPremultiplied, null );
        } else target = new BufferedImage( targetW, targetH, type );
        Graphics2D g = target.createGraphics();
        g.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );
        g.drawRenderedImage( source, AffineTransform.getScaleInstance( sx, sy ) );
        g.dispose();
        return target;
    }

    public static String getValue(HttpServletRequest request, String s) {
        return ((request.getParameter( s ) == null) ? ("") : (request.getParameter( s ).trim()));
    }


    public static String getPath() throws UnsupportedEncodingException {
        String strRealPath = new tool().getClass().getClassLoader().getResource( "" ).getFile();
        strRealPath = URLDecoder.decode( strRealPath, "utf-8" );
        String str = strRealPath.split( "/jjlife" )[0];
        String url = str;
        if (str.indexOf( "/" ) == 0) {
            url = str.substring( 1 ) + "/jjlife";
        }
        return url;
    }

    //将string类型的日期转为date
    public static Date parse(String strDate) {
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" );
        try {
            return sdf.parse( strDate );
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    //获取用户手机号
    public static String getPhoneNumber(String encryptedData, String sessionkey, String iv) {
        JSONObject jsObj = decrypt( encryptedData, sessionkey, iv );
        return jsObj.getString( "phoneNumber" );
    }

    public static JSONObject decrypt(String encryptedData, String sessionkey, String iv) {
        // 被加密的数据
        byte[] dataByte = Base64.decodeFast( encryptedData );
        // 加密秘钥
        byte[] keyByte = Base64.decodeFast( sessionkey );
        // 偏移量
        byte[] ivByte = Base64.decodeFast( iv );
        try {
            // 如果密钥不足16位，那么就补足. 这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill( temp, (byte) 0 );
                System.arraycopy( keyByte, 0, temp, 0, keyByte.length );
                keyByte = temp;
            }
            // 初始化
            Security.addProvider( new BouncyCastleProvider() );
            Cipher cipher = Cipher.getInstance( "AES/CBC/PKCS7Padding", "BC" );
            SecretKeySpec spec = new SecretKeySpec( keyByte, "AES" );
            AlgorithmParameters parameters = AlgorithmParameters.getInstance( "AES" );
            parameters.init( new IvParameterSpec( ivByte ) );
            cipher.init( Cipher.DECRYPT_MODE, spec, parameters );// 初始化
            byte[] resultByte = cipher.doFinal( dataByte );
            if (null != resultByte && resultByte.length > 0) {
                String result = new String( resultByte, "UTF-8" );
                return JSONObject.parseObject( result );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
